package com.example.question.tree.tree2;

import com.example.question.tree.tree1.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class Code02_222 {
    public static void main(String[] args) {

    }

    public int countNodes1(TreeNode root) {
        return bfs(root);
    }

    public int bfs(TreeNode node) {
        int count = 0;
        if (node == null) {
            return count;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(node);
        while (!queue.isEmpty()) {
            int size = queue.size();
            count += size;
            for (int i = 0; i < size; i++) {
                TreeNode treeNode = queue.poll();
                if (treeNode.left != null) {
                    queue.add(treeNode.left);
                }
                if (treeNode.right != null) {
                    queue.add(treeNode.right);
                }
            }
        }
        return count;
    }

    private int max = 0;

    public int countNodes2(TreeNode root) {
        preOrder(root, 1);
        return max;

    }

    public void preOrder(TreeNode node, int seq) {
        if (node == null) {
            return;
        }
        max = Math.max(max, seq);
        preOrder(node.left, 2 * seq);
        preOrder(node.right, 2 * seq + 1);
    }

    public int countNodes(TreeNode root) {
        return postOrder(root, 1);
    }

    public int postOrder(TreeNode node, int seq) {
        if (node == null) {
            return 0;
        }
        if (node.left == null && node.right == null) {
            return seq;
        }
        int left = postOrder(node.left, seq * 2);
        int right = postOrder(node.right, seq * 2 + 1);
        return Math.max(left, right);
    }
}
